<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ws连接测试-视图</title>
    <script src="socket.io.js"></script>
    <link rel="stylesheet" type="text/css" href="view.css" />
  </head>
  <body>
    <div id="main">
      <div id="peo" style="transform: translate3d(1px,2px,0px);"></div>
    </div>
    <div id="info">
      连接中...
    </div>
  </body>
</html>

<script>
  //var ws = io.connect('http://10.8.76.74:9092/');
  var ws = io.connect('http://192.168.31.113:9092/');
  var $info = document.getElementById("info");
  var $peo = document.getElementById("peo");

  //动作
  function peoAction(msg) {
    var dis = 2; //每次移动像素
    var translate3dAry = $peo.style.transform.replace("translate3d(","").split("px,");
    var x = Number(translate3dAry[0]);
    var y = Number(translate3dAry[1]);
    switch (msg) {
      case "up":
        y -= dis;
        break;
      case "down":
        y += dis;
        break;
      case "left":
        x -= dis;
        break;
      case "right":
        x += dis;
        break;
    }
    //console.log(x,y);
    $peo.style.transform = "translate3d(" + x + "px," + y + "px,0px)";
  }


  ws.on('connect', function() {
    console.log("veiw连接成功");
    $info.innerHTML = "连接成功";
    setTimeout(function() {
      $info.style.display = "none";
    }, 2000)

    //标记view页面
    ws.emit('setViewName', true);
  })

  //接收到服务器发布的信息
  ws.on('viewMessage', function(msg) {
    //console.log("接收到服务器发布的信息", msg);
    peoAction(msg)
  })

  ws.on('error', function() {
    console.log('ws错误:', ws);
    ws.disconnect();
  })
</script>
